package 树.遍历;

import 抽象数据类型.TreeNode;

import java.util.LinkedList;
import java.util.Stack;

public class PreTraverse {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.left.right = new TreeNode(8);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);
        root.right.right.right = new TreeNode(9);
        preOrderTraverse(root);
        for (Object o : list) {
            System.out.println(((TreeNode)o).getVal());
        }

    }

    public static void preOrderTraverse(TreeNode root) {
        System.out.println("\n前序遍历");
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                System.out.print(root.val);
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            root = root.right;
        }
    }
}
